//
//  KXPath.m
//  Ghac 4S
//
//  Created by apple on 11-9-7.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "KXPath.h"
#import "RegexKitLite.h"
@implementation KXPath
@synthesize keyList = m_pathList;
@synthesize predicate = m_predicateKey;
-(id)initWithArray:(NSArray *)keyList predicate:(NSString*)predicateWord
{
    if ((self = [super init]))
    {
        NSMutableArray* array = [[NSMutableArray alloc] init];
        for(NSString* key in keyList)
        {
            
            NSPredicate* predicate = [NSPredicate predicateWithFormat:@"__name__ == %@", key];
            [array addObject:predicate];
        }
        m_pathList = array;
        
        // form a comparePredicateKey;
        if (predicateWord != Nil)
        {
            
            NSString* attributesRegex = [[NSString alloc] initWithFormat:@"(@)(\\w+%@)", KP_OPERATOR_REGEX];
            NSString* regex = [[NSString alloc] initWithFormat:@"(([\\w\\.]+\\.\\w+)|(\\A\\w+)|([^@]\\b\\w+))(%@)", KP_OPERATOR_REGEX];
            NSString* tmp = [predicateWord stringByReplacingOccurrencesOfRegex:regex withString:@"$1.__nodeValue__$5"];
            tmp = [tmp stringByReplacingOccurrencesOfRegex:attributesRegex withString:@"__attributes__.$2"];
            m_predicateKey = [NSPredicate predicateWithFormat:tmp];
            [attributesRegex release];
            [regex release];
        }
        
        
    }
    return self;
}
-(id)initWithString:(NSString *)listString  predicate:(NSString*)predicateWord
{
    return [self initWithArray:[listString componentsSeparatedByString:@"."] predicate:predicateWord];
}
+(id)kXPathByString:(NSString *)listString predicate:(NSString *)predicateWord
{
    KXPath* path = [[KXPath alloc] initWithString:listString predicate:predicateWord];
    return [path autorelease];
}
-(NSPredicate*)predicatePathAtIndex:(NSUInteger)index;
{
    return [m_pathList objectAtIndex:index];
}
-(NSUInteger)length
{
    return [m_pathList count];
}
-(NSArray *)keyList
{
    return nil;
}
-(NSString *)keyString
{
    return [m_pathList componentsJoinedByString:@"."];
}
- (NSString *)keyAtIndex:(NSUInteger)index
{
    NSLog(@"KXPath::keyAtIndex not complete");
    return Nil;
}
-(void)dealloc
{
    if (m_pathList.retainCount)
    {
        [m_pathList release];
    }
    [super dealloc];
}
@end
